<template>
  <div class="square-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>社区广场</h2>
      <p>发现其他用户分享的精彩提示词和创作</p>
    </div>

    <!-- 筛选和排序 -->
    <div class="filter-section">
      <div class="filter-tabs">
        <el-button 
          v-for="tab in tabs" 
          :key="tab.key"
          :type="activeTab === tab.key ? 'primary' : ''"
          @click="activeTab = tab.key"
          class="filter-tab"
        >
          {{ tab.label }}
        </el-button>
      </div>
      
      <div class="sort-options">
        <el-select v-model="sortBy" placeholder="排序方式" size="small">
          <el-option label="最新发布" value="latest"></el-option>
          <el-option label="最多点赞" value="likes"></el-option>
          <el-option label="最多评论" value="comments"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 提示词卡片列表 -->
    <div class="prompt-cards-grid">
      <div 
        v-for="item in displayPrompts" 
        :key="item.id"
        class="prompt-card"
      >
        <!-- 卡片头部：用户信息 -->
        <div class="card-header">
          <el-avatar :size="36" :src="item.user.avatar"></el-avatar>
          <div class="user-info">
            <div class="user-name">{{ item.user.name }}</div>
            <div class="post-time">{{ formatTime(item.time) }}</div>
          </div>
          <el-dropdown>
            <el-button class="more-button" circle>
              <MoreFilled />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>举报</el-dropdown-item>
                <el-dropdown-item>不感兴趣</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 卡片内容：提示词和预览 -->
        <div class="card-content">
          <div class="prompt-text">{{ item.prompt }}</div>
          <div class="preview-container">
            <div class="preview-image" :style="{ backgroundImage: `url(${item.previewImage})` }" @click="navigateToDetail(item)"></div>
          </div>
          <div class="platform-tags">
            <el-tag 
              v-for="platform in item.platforms" 
              :key="platform"
              size="small"
              effect="plain"
              class="platform-tag"
            >
              {{ platform }}
            </el-tag>
          </div>
        </div>

        <!-- 卡片底部：互动统计 -->
        <div class="card-footer">
              <div class="interaction-stats">
                <div class="stat-item" @click="toggleLike(item)">
                  <StarFilled v-if="item.liked" class="icon liked-icon" />
                  <Star v-else class="icon" />
                  <span>{{ item.likes }}</span>
                </div>
                <div class="stat-item" @click="showComments(item)">
                  <ChatDotRound class="icon" />
                  <span>{{ item.comments }}</span>
                </div>
                <div class="stat-item" @click="copyPrompt(item.prompt)">
                  <DocumentCopy class="icon" />
                  <span>复制</span>
                </div>
                <div class="stat-item" @click="usePrompt(item.prompt)">
                  <VideoPlay class="icon use-icon" />
                  <span>使用</span>
                </div>
              </div>
            </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div class="load-more">
      <el-button 
        type="primary" 
        :loading="loading"
        @click="loadMore"
        :disabled="loading || displayPrompts.length >= allPrompts.length"
      >
        {{ displayPrompts.length >= allPrompts.length ? '没有更多了' : '加载更多' }}
      </el-button>
    </div>

    <!-- 评论对话框 -->
    <el-dialog 
      :title="'评论 (' + currentComments.length + ')'" 
      v-model="showCommentDialog"
      width="60%"
    >
      <div class="comment-dialog-content">
        <!-- 当前帖子信息 -->
        <div class="comment-post-preview">
          <div class="comment-post-prompt">{{ currentPost.prompt }}</div>
        </div>
        
        <!-- 评论输入 -->
        <div class="comment-input-area">
          <el-input 
            v-model="newCommentText" 
            type="textarea"
            placeholder="写下你的评论..."
            :rows="3"
            show-word-limit
            maxlength="200"
          ></el-input>
          <el-button 
            type="primary" 
            @click="submitComment"
            :disabled="!newCommentText.trim()"
            class="submit-comment-btn"
          >
            发表评论
          </el-button>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div v-if="currentComments.length === 0" class="no-comments">
            暂无评论，快来发表第一条评论吧！
          </div>
          <div v-else 
            v-for="comment in currentComments" 
            :key="comment.id"
            class="comment-item"
          >
            <el-avatar :size="28" :src="comment.user.avatar"></el-avatar>
            <div class="comment-details">
              <div class="comment-header">
                <span class="comment-author">{{ comment.user.name }}</span>
                <span class="comment-time">{{ formatTime(comment.time) }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { 
  MoreFilled, Star, StarFilled, ChatDotRound, DocumentCopy,
  Share, Filter, Calendar, Rank, Collection, CollectionTag,
  Delete, Edit, VideoPlay, TopRight, Check
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'Square',
  components: {
    MoreFilled,
    Star,
    StarFilled,
    ChatDotRound,
    DocumentCopy,
    Share,
    Filter,
    Calendar,
    Rank,
    Collection,
    CollectionTag,
    Delete,
    Edit,
    VideoPlay,
    TopRight,
    Check
  },
  setup() {
    const router = useRouter()
    // 页面数据
    const activeTab = ref('all')
    const sortBy = ref('latest')
    const loading = ref(false)
    const itemsPerPage = 6
    const displayCount = ref(itemsPerPage)
    const showCommentDialog = ref(false)
    const newCommentText = ref('')
    const currentPost = ref({})
    const currentComments = ref([])
    
    // 导航到详情页
    const navigateToDetail = (item) => {
      router.push({
        path: '/home',
        query: { prompt: item.prompt, previewImage: item.previewImage }
      })
    }

    // 标签页数据
    const tabs = [
      { key: 'all', label: '全部' },
      { key: 'image', label: '图像生成' },
      { key: 'text', label: '文本生成' },
      { key: 'audio', label: '音频生成' }
    ]

    // 模拟提示词数据
    const allPrompts = ref([
      {
        id: 1,
        prompt: '一只可爱的小猫在阳光下睡觉，高清细节，逼真风格',
        platforms: ['豆包', '通义'],
        previewImage: 'https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?w=500&auto=format&fit=crop',
        user: {
          name: 'AI爱好者',
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
        },
        likes: 128,
        comments: 24,
        time: new Date('2024-01-15T10:30:00'),
        liked: false
      },
      {
        id: 2,
        prompt: '城市夜景，霓虹灯闪烁，赛博朋克风格，未来感十足',
        platforms: ['即梦', '豆包'],
        previewImage: 'https://images.unsplash.com/photo-1546436836-07a91091f160?w=500&auto=format&fit=crop',
        user: {
          name: '创意无限',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        likes: 256,
        comments: 42,
        time: new Date('2024-01-15T09:15:00'),
        liked: true
      },
      {
        id: 3,
        prompt: '山水画，宁静的湖泊和远山，中国传统水墨画风格',
        platforms: ['通义', '即梦'],
        previewImage: 'https://images.unsplash.com/photo-1533227268428-f9ed0900fb3b?w=500&auto=format&fit=crop',
        user: {
          name: '水墨大师',
          avatar: 'https://cube.elemecdn.com/1/8e/aeffeb4de2fc1c79c96e8159975fepng.png'
        },
        likes: 89,
        comments: 15,
        time: new Date('2024-01-14T16:45:00'),
        liked: false
      },
      {
        id: 4,
        prompt: '未来科技城市，飞行汽车和高楼，细节丰富，科幻风格',
        platforms: ['豆包', '通义'],
        previewImage: 'https://images.unsplash.com/photo-1504384308090-c894fdcc538d?w=500&auto=format&fit=crop',
        user: {
          name: '科幻迷',
          avatar: 'https://cube.elemecdn.com/2/11/6535b3258e081e88d7d5f82a629a5jpeg.jpeg'
        },
        likes: 176,
        comments: 31,
        time: new Date('2024-01-14T14:20:00'),
        liked: false
      },
      {
        id: 5,
        prompt: '一杯精致的拿铁咖啡，拉花精美，温暖的咖啡馆环境',
        platforms: ['即梦', '豆包'],
        previewImage: 'https://images.unsplash.com/photo-1512568400610-62da28bc8a13?w=500&auto=format&fit=crop',
        user: {
          name: '咖啡控',
          avatar: 'https://cube.elemecdn.com/4/28/7f30ef589a4e94772c811c1a66651jpeg.jpeg'
        },
        likes: 64,
        comments: 12,
        time: new Date('2024-01-13T11:30:00'),
        liked: true
      },
      {
        id: 6,
        prompt: '神秘的森林，雾气缭绕，阳光透过树叶洒下金色光斑',
        platforms: ['通义'],
        previewImage: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=500&auto=format&fit=crop',
        user: {
          name: '自然探索者',
          avatar: 'https://cube.elemecdn.com/5/20/6a0ddb33de4855567d177151b0149jpeg.jpeg'
        },
        likes: 143,
        comments: 28,
        time: new Date('2024-01-13T09:15:00'),
        liked: false
      },
      {
        id: 7,
        prompt: '宇航员在月球表面，地球在背景中，真实感，高细节',
        platforms: ['豆包', '即梦'],
        previewImage: 'https://images.unsplash.com/photo-1462331940025-496dfbfc7564?w=500&auto=format&fit=crop',
        user: {
          name: '太空漫游者',
          avatar: 'https://cube.elemecdn.com/6/44/3052716fc5e70f51277d6b3078190jpeg.jpeg'
        },
        likes: 215,
        comments: 37,
        time: new Date('2024-01-12T15:45:00'),
        liked: false
      },
      {
        id: 8,
        prompt: '可爱的卡通角色，大眼睛，彩色头发，活泼风格',
        platforms: ['通义', '豆包'],
        previewImage: 'https://images.unsplash.com/photo-1533575770077-052fa2c609fc?w=500&auto=format&fit=crop',
        user: {
          name: '动漫爱好者',
          avatar: 'https://cube.elemecdn.com/7/8e/3e201e13453882e6d6b78e794ee0ajpeg.jpeg'
        },
        likes: 189,
        comments: 33,
        time: new Date('2024-01-12T13:20:00'),
        liked: true
      }
    ])

    // 模拟评论数据
    const commentData = {
      1: [
        {
          id: 101,
          content: '这个提示词太棒了，生成的猫咪很逼真！',
          user: {
            name: '用户A',
            avatar: 'https://cube.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bb1ejpeg.jpeg'
          },
          time: new Date('2024-01-15T11:00:00')
        },
        {
          id: 102,
          content: '我也试了一下，效果真的不错',
          user: {
            name: '用户B',
            avatar: 'https://cube.elemecdn.com/9/13/1a0a2433f235294b46775129b33cajpeg.jpeg'
          },
          time: new Date('2024-01-15T10:30:00')
        }
      ],
      2: [
        {
          id: 201,
          content: '赛博朋克风格很炫酷',
          user: {
            name: '用户C',
            avatar: 'https://cube.elemecdn.com/a/6a/3e102a556969b962827e6a8c4009djpeg.jpeg'
          },
          time: new Date('2024-01-15T10:00:00')
        }
      ]
    }

    // 计算显示的提示词列表
    const displayPrompts = computed(() => {
      let filtered = allPrompts.value
      
      // 根据标签页筛选
      if (activeTab.value !== 'all') {
        // 这里可以根据类型进行更复杂的筛选
        filtered = filtered.filter(p => p.id % 2 === 0)
      }
      
      // 排序
      const sorted = [...filtered].sort((a, b) => {
        switch (sortBy.value) {
          case 'latest':
            return new Date(b.time) - new Date(a.time)
          case 'likes':
            return b.likes - a.likes
          case 'comments':
            return b.comments - a.comments
          default:
            return new Date(b.time) - new Date(a.time)
        }
      })
      
      // 返回分页数据
      return sorted.slice(0, displayCount.value)
    })

    // 加载更多
    const loadMore = () => {
      if (loading.value || displayCount.value >= allPrompts.value.length) return
      
      loading.value = true
      setTimeout(() => {
        displayCount.value += itemsPerPage
        loading.value = false
      }, 1000)
    }

    // 切换点赞状态
    const toggleLike = (item) => {
      item.liked = !item.liked
      item.likes += item.liked ? 1 : -1
    }

    // 显示评论对话框
    const showComments = (post) => {
      currentPost.value = post
      currentComments.value = commentData[post.id] || []
      showCommentDialog.value = true
    }

    // 提交评论
    const submitComment = () => {
      if (!newCommentText.value.trim()) return
      
      const newComment = {
        id: Date.now(),
        content: newCommentText.value,
        user: {
          name: 'AI助手',
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
        },
        time: new Date()
      }
      
      currentComments.value.push(newComment)
      
      // 更新原数据中的评论数
      const post = allPrompts.value.find(p => p.id === currentPost.value.id)
      if (post) {
        post.comments++
      }
      
      newCommentText.value = ''
    }

    // 复制提示词
    const copyPrompt = async (prompt) => {
      try {
        await navigator.clipboard.writeText(prompt)
        ElMessage.success('提示词已复制到剪贴板')
      } catch (err) {
        ElMessage.error('复制失败，请手动复制')
      }
    }

    // 使用提示词 - 自动打开多个AI生成网站
    const usePrompt = (prompt) => {
      if (!prompt) {
        ElMessage.warning('提示词为空，无法使用！')
        return;
      }

      // 编码提示词用于URL参数
      const encodedPrompt = encodeURIComponent(prompt);
      
      // 定义支持的AI生成网站列表及其URL模板
      const aiPlatforms = [
        {
          name: 'DALL-E (OpenAI)',
          url: `https://labs.openai.com/dalle?prompt=${encodedPrompt}`
        },
        {
          name: 'Midjourney (Discord)',
          url: 'https://discord.com/channels/@me'
        },
        {
          name: 'Stable Diffusion (Hugging Face)',
          url: `https://huggingface.co/spaces/stabilityai/stable-diffusion`
        },
        {
          name: 'Craiyon (前DALL-E Mini)',
          url: `https://www.craiyon.com/?prompt=${encodedPrompt}`
        }
      ];

      // 显示确认对话框
      const confirmation = confirm(`即将在新标签页中打开以下${aiPlatforms.length}个网站：\n${aiPlatforms.map(p => p.name).join('\n')}\n\n提示词已复制到剪贴板，请在各网站中粘贴使用。`);
      
      if (confirmation) {
        // 复制提示词到剪贴板
        navigator.clipboard.writeText(prompt).then(() => {
          console.log('提示词已复制到剪贴板');
          ElMessage.success('提示词已复制到剪贴板！');
          
          // 打开每个平台的网站
          aiPlatforms.forEach((platform, index) => {
            // 使用延时打开，避免浏览器阻止多个弹窗
            setTimeout(() => {
              window.open(platform.url, '_blank');
            }, 300 * index);
          });
          
        }).catch(err => {
          console.error('复制到剪贴板失败:', err);
          ElMessage.error('复制失败，请手动复制');
          
          // 即使复制失败，仍然尝试打开网站
          aiPlatforms.forEach((platform, index) => {
            setTimeout(() => {
              window.open(platform.url, '_blank');
            }, 300 * index);
          });
        });
      }
    }

    // 格式化时间
    const formatTime = (time) => {
      const now = new Date()
      const target = new Date(time)
      const diffMs = now - target
      const diffMins = Math.floor(diffMs / 60000)
      const diffHours = Math.floor(diffMins / 60)
      const diffDays = Math.floor(diffHours / 24)
      
      if (diffMins < 60) {
        return `${diffMins}分钟前`
      } else if (diffHours < 24) {
        return `${diffHours}小时前`
      } else if (diffDays < 7) {
        return `${diffDays}天前`
      } else {
        return target.toLocaleDateString()
      }
    }

    return {
      activeTab,
      tabs,
      sortBy,
      loading,
      displayPrompts,
      allPrompts,
      showCommentDialog,
      currentPost,
      currentComments,
      newCommentText,
      loadMore,
      toggleLike,
      showComments,
      submitComment,
      copyPrompt,
      usePrompt,
      formatTime,
      navigateToDetail
    }
  }
}
</script>

<style scoped>
.square-container {
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h2 {
  font-size: 32px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 20px;
}

.filter-tabs {
  display: flex;
  gap: 10px;
}

.filter-tab {
  border-radius: 20px;
  padding: 8px 20px;
  transition: all 0.3s;
}

.prompt-cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.prompt-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  padding: 20px;
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid #ebeef5;
}

.prompt-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.12);
  border-color: #409eff;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.card-header .user-info {
  flex: 1;
  margin-left: 12px;
}

.user-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.more-button {
  background-color: transparent;
  border: none;
  color: #909399;
}

.more-button:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

.card-content {
  margin-bottom: 16px;
}

.prompt-text {
  font-size: 16px;
  color: #303133;
  line-height: 1.6;
  margin-bottom: 16px;
  word-break: break-word;
}

.preview-container {
  margin-bottom: 12px;
  border-radius: 8px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 200px;
  background-size: cover;
  background-position: center;
  background-color: #f5f7fa;
  transition: transform 0.3s;
}

.prompt-card:hover .preview-image {
  transform: scale(1.03);
}

.platform-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.platform-tag {
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #d9ecff;
}

.card-footer {
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}

.interaction-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  cursor: pointer;
  transition: color 0.3s;
}

.stat-item:hover {
  color: #409eff;
}

.icon {
  font-size: 16px;
}

.liked-icon {
    color: #f56c6c;
  }

  .use-icon {
    color: #409eff;
  }

  .use-icon:hover {
    color: #66b1ff;
  }

.load-more {
  text-align: center;
  margin: 40px 0;
}

/* 评论对话框样式 */
.comment-dialog-content {
  padding: 10px 0;
}

.comment-post-preview {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.comment-post-prompt {
  font-size: 16px;
  color: #303133;
  line-height: 1.5;
}

.comment-input-area {
  margin-bottom: 20px;
}

.submit-comment-btn {
  margin-top: 10px;
}

.comment-list {
  max-height: 400px;
  overflow-y: auto;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-details {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #409eff;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  word-break: break-word;
}

.no-comments {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .square-container {
    padding: 10px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-tabs {
    justify-content: center;
  }
  
  .prompt-cards-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .preview-image {
    height: 180px;
  }
  
  .interaction-stats {
    justify-content: space-around;
    gap: 16px;
  }
}
</style>